<template>
	<view class="avatar-page">
		<!-- 背景装饰元素 -->
		<view class="decor-circle circle-1"></view>
		<view class="decor-circle circle-2"></view>
		<view class="decor-circle circle-3"></view>

		<!-- 加载动画 - 右下角悬浮 -->
		<view class="loading-container" v-if="isshow">
			<!-- <loading2></loading2> -->
			<loading3></loading3>
		</view>

		<!-- 主内容区 -->
		<view class="content-wrapper">
			<!-- 标题 -->
			<view class="title-container">
				<text class="title">修改头像</text>
				<text class="subtitle">上传你的个性头像</text>
			</view>

			<!-- 头像展示区 -->
			<view class="avatar-display">
				<view class="avatar-frame">
					<image class="avatar" :src="croppedImage || avatarUrl" mode="aspectFill"></image>
				</view>
				<view class="avatar-shadow"></view>
			</view>

			<!-- 操作按钮区 -->
			<view class="action-buttons">
				<selectPicture @success="handleSuccess" @cancel="handleCancel" circle>
					<button class="upload-btn select-btn">
						<text class="iconfont icon-image"></text>
						<text>选择图片</text>
					</button>
				</selectPicture>

				<button v-if="croppedImage && !uploadSuccess" class="upload-btn confirm-btn" :disabled="isUploading"
					@click="confirmUpload" style="color:#007aff ,border-style: double;">
					<text class="iconfont icon-upload"></text>
					<text>{{ isUploading ? `上传中 ${uploadProgress}%` : '确认上传' }}</text>
				</button>
			</view>

			<!-- 进度条 -->
			<view class="progress-container" v-if="isUploading">
				<view class="progress-info">
					<text class="progress-text">上传进度</text>
					<text class="progress-percent">{{ uploadProgress }}%</text>
				</view>
				<view class="progress-bar">
					<view class="progress-fill" :style="{ width: uploadProgress + '%', background: progressGradient }">
					</view>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	import selectPictureVue from '@/components/selectPicture/selectPicture.vue'

	export default {
		data() {
			return {
				tempImagePath: "", // 选择的图片路径
				croppedImage: "", // 裁剪后的图片路径
				showCropper: false, // 是否显示裁剪器
				isUploading: false, // 是否正在上传
				uploadProgress: 0, // 上传进度
				position: {
					x: 0,
					y: 0
				}, // 记录拖动位置
				student: {},
				uploadSuccess: false, // 上传成功标志
				imageInfo: null, // 存储图片信息
				displayWidth: 300, // 图片显示宽度
				displayHeight: 300, // 图片显示高度
				progressGradient: 'linear-gradient(to right, #4361ee, #f72585)',
				isshow: true
			};
		},
		computed: {
			uploadButtonStyle() {
				return {
					background: `linear-gradient(to right, #4CAF50 ${this.uploadProgress}%, #ddd ${this.uploadProgress}%)`,
					color: this.isUploading ? "#fff" : "#000", // 上传时文字变白
					transition: "background 0.2s ease-in-out",
				};
			}
		},
		onLoad() {
			let that = this;
			// 获取用户信息
			uni.getStorage({
				key: 'teacher',
				success: function(res) {
					that.student = res.data;
				}
			});
		},
		computed: {
			avatarUrl() {
				// console.log(this.student.avatarUrl)
				let basePath = globalVariable + "/get/" + this.student.avatarUrl || "/static/aver.jpg";
				return basePath + "?t=" + new Date().getTime(); // 加时间戳
			}

		},
		methods: {
			// 处理图片选择成功
			handleSuccess(file) {
				console.log(file);
				this.croppedImage = file.tempFilePath; // 先把图片显示到预览框
				this.uploadSuccess = false; // 显示“确认上传”按钮
			},
			// 新增图片压缩方法
			compressImage(filePath) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: filePath,
						success: (info) => {
							const quality = 0.7; // 压缩质量0-1
							const maxWidth = 800; // 最大宽度
							const maxHeight = 800; // 最大高度

							let width = info.width;
							let height = info.height;

							// 计算缩放比例
							if (width > maxWidth || height > maxHeight) {
								const ratio = Math.min(maxWidth / width, maxHeight / height);
								width = width * ratio;
								height = height * ratio;
							}

							// 使用canvas压缩图片
							const ctx = uni.createCanvasContext('compressCanvas', this);
							ctx.drawImage(filePath, 0, 0, width, height);
							ctx.draw(false, () => {
								uni.canvasToTempFilePath({
									canvasId: 'compressCanvas',
									quality: quality,
									success: (res) => {
										resolve(res.tempFilePath);
									},
									fail: (err) => {
										console.error('压缩失败:', err);
										reject(err);
									}
								}, this);
							});
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 确认上传
			confirmUpload() {
				if (!this.croppedImage) {
					uni.showToast({
						title: "请先选择图片",
						icon: "none"
					});
					return;
				}

				this.isUploading = true;
				this.uploadProgress = 0; // 进度重置
				this.uploadImage(this.croppedImage)
					.then((serverPath) => {
						let flag = JSON.parse(serverPath);
						if (flag.status == 1) {
							this.isUploading = false;
							this.uploadSuccess = true; // 上传成功后按钮消失
							this.student.aver = flag.data; // 更新头像
							uni.showToast({
								title: "上传成功",
								icon: "success"
							});

							// 更新本地存储的 studentInfo
							let studentInfo = uni.getStorageSync("studentInfo") || {};
							studentInfo.aver = flag.data;
							uni.setStorageSync("studentInfo", studentInfo);
						} else {
							this.isUploading = false;
							uni.showToast({
								title: "上传失败",
								icon: "error"
							});
						}
					})
					.catch((err) => {
						this.isUploading = false;
						console.error("上传失败:", err);
						uni.showToast({
							title: "上传失败",
							icon: "none"
						});
					});
			},

			// 上传图片（带进度）
			uploadImage(localPath) {
				return new Promise((resolve, reject) => {
					const teacher = uni.getStorageSync("teacher");
					const uploadTask = uni.uploadFile({
						url: globalVariable + "/uploadTeacherAver",
						filePath: localPath,
						name: "file",
						formData: {
							teacher: JSON.stringify(teacher)
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data);
							} else {
								reject("上传失败");
							}
						},
						fail: (err) => {
							reject(err);
						}
					});

					// 监听上传进度
					uploadTask.onProgressUpdate((progress) => {
						this.uploadProgress = progress.progress;
					});
				});
			},
			// 点击取消的回调
			handleCancel() {
				// 没有参数
			},
			zoomIn() {
				this.displayWidth *= 1.1;
				this.displayHeight *= 1.1;
			},
			zoomOut() {
				this.displayWidth *= 0.9;
				this.displayHeight *= 0.9;
			},
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sourceType: ["album", "camera"],
					success: (res) => {
						this.tempImagePath = res.tempFilePaths[0]; // 存储选择的图片
						// 获取图片信息
						uni.getImageInfo({
							src: res.tempFilePaths[0],
							success: (imageInfo) => {
								this.imageInfo = imageInfo;
								// 计算图片显示尺寸
								const displaySize = this.calculateDisplaySize(imageInfo.width,
									imageInfo.height);
								this.displayWidth = displaySize.width;
								this.displayHeight = displaySize.height;
								this.showCropper = true; // 显示裁剪弹窗
								this.uploadSuccess = false; // 重新选择图片后，重新允许上传
							}
						});
					}
				});
			},

			// 计算图片显示尺寸
			calculateDisplaySize(width, height) {
				const maxSize = 600; // 裁剪框的最大尺寸
				let displayWidth = width;
				let displayHeight = height;

				// 计算缩放比例，确保图片至少填满容器
				const containerWidth = 300;
				const containerHeight = 300;

				const scaleX = containerWidth / width;
				const scaleY = containerHeight / height;
				const scale = Math.max(scaleX, scaleY);

				displayWidth = width * scale;
				displayHeight = height * scale;

				return {
					width: displayWidth,
					height: displayHeight
				};
			},

			// 更新拖动位置
			updatePosition(e) {
				this.position.x = e.detail.x;
				this.position.y = e.detail.y;
			},

			// 取消裁剪
			cancelCrop() {
				this.showCropper = false;
			},

			// 确认裁剪（实际裁剪）
			confirmCrop() {
				const ctx = uni.createCanvasContext('cropperCanvas', this);
				const imageWidth = 300;
				const imageHeight = 300;

				// 直接绘制预览窗口中的内容
				ctx.drawImage(this.tempImagePath,
					-this.position.x,
					-this.position.y,
					this.displayWidth,
					this.displayHeight,
					0,
					0,
					imageWidth,
					imageHeight
				);

				ctx.draw(false, () => {
					// 将canvas转换为图片
					uni.canvasToTempFilePath({
						canvasId: 'cropperCanvas',
						success: (res) => {
							this.croppedImage = res.tempFilePath;
							this.showCropper = false;
						},
						fail: (err) => {
							console.error('裁剪失败:', err);
							uni.showToast({
								title: '裁剪失败',
								icon: 'none'
							});
						}
					}, this);
				});
			},

			// // 上传头像
			// confirmUpload() {
			// 	let that = this;
			// 	if (!this.croppedImage) {
			// 		uni.showToast({
			// 			title: "请先选择图片",
			// 			icon: "none"
			// 		});
			// 		return;
			// 	}

			// 	this.isUploading = true;
			// 	this.uploadImage(this.croppedImage)
			// 		.then((serverPath) => {
			// 			let flag = JSON.parse(serverPath)
			// 			if (flag.status == 1) {
			// 				this.isUploading = false;
			// 				this.student.aver = serverPath; // 更新头像URL
			// 				this.uploadSuccess = true; // 设置上传成功
			// 				uni.showToast({
			// 					title: "上传成功",
			// 					icon: "success"
			// 				});
			// 				/// 更新 localStorage 里的 studentInfo
			// 				let studentInfo = uni.getStorageSync("studentInfo") || {};
			// 				console.log("更新后的数据为" + JSON.parse(serverPath).data)
			// 				studentInfo.aver = JSON.parse(serverPath).data;
			// 				uni.setStorageSync("studentInfo", studentInfo);
			// 			} else {
			// 				uni.showToast({
			// 					title: "上传失败",
			// 					icon: "success"
			// 				});
			// 			}

			// 		})
			// 		.catch((err) => {
			// 			this.isUploading = false;
			// 			console.error("上传失败:", err);
			// 			uni.showToast({
			// 				title: "上传失败",
			// 				icon: "none"
			// 			});
			// 		});
			// },


			// // 上传图片逻辑（带进度）
			// uploadImage(localPath) {
			// 	return new Promise((resolve, reject) => {
			// 		const studentInfo = uni.getStorageSync("studentInfo"); // 获取用户信息
			// 		const uploadTask = uni.uploadFile({
			// 			url: globalVariable._value + "/upload",
			// 			filePath: localPath,
			// 			name: "file",
			// 			formData: {
			// 				studentInfo: JSON.stringify(studentInfo)
			// 			},
			// 			success: (res) => {
			// 				if (res.statusCode === 200) {
			// 					resolve(res.data);
			// 				} else {
			// 					reject("上传失败");
			// 				}
			// 			},
			// 			fail: (err) => {
			// 				reject(err);
			// 			}
			// 		});

			// 		// 监听上传进度
			// 		uploadTask.onProgressUpdate((progress) => {
			// 			this.uploadProgress = progress.progress;
			// 		});
			// 	});
			// }
		}
	};
</script>

<style scoped>
	.cropper-controls {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 15px;
		padding: 15px 20px;
		background-color: #fff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-top: 40rpx;
	}

	.cropper-controls button {
		flex: 1;
		padding: 12px 0;
		border: none;
		border-radius: 5px;
		/* font-size: 16px; */
		text-align: center;
		cursor: pointer;
		transition: background-color 0.3s ease;
		background-color: #fffcfc;
		display: flex;
		align-items: center;
		justify-content: center;
		/* color: white; */
	}

	.zoom-in-btn {
		background-color: #4caf50;
	}

	.zoom-out-btn {
		background-color: #f44336;
	}

	.avatar-page {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.title {
		font-size: 22px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.avatar-container {
		width: 150px;
		height: 150px;
		border-radius: 50%;
		overflow: hidden;
		border: 3px solid #ddd;
		margin-bottom: 20px;
	}

	.avatar {
		width: 100%;
		height: 100%;
		display: block;
	}

	.upload-btn,
	.confirm-btn {
		background-color: #007aff;
		color: #007aff;
		padding: 12px 20px;
		border-radius: 10px;
		font-size: 16px;
		margin-top: 10px;
		width: 200px;
		text-align: center;
	}

	.confirm-btn {
		background-color: #ffffff;
		border-style: double;
		border-color: #007aff;
	}



	.upload-status {
		font-size: 14px;
		color: #333;
		margin-top: 5px;
	}

	/* 裁剪区域 */
	.cropper-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.cropper-container {
		position: relative;
		width: 80vw;
		height: 80vw;
		max-width: 400px;
		max-height: 400px;
		background: #000;
		border-radius: 10px;
		overflow: hidden;
		box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
	}

	.movable-area {
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;
		background: #000;
	}

	.movable-image {
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
	}

	/* 底部操作栏容器 */
	.cropper-controls {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 15px 20px;
		/* background-color: #fff; */
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
	}

	/* 按钮样式 */
	.cropper-controls button {
		flex: 1;
		margin: 0 10px;
		padding: 12px 0;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		color: white;
		text-align: center;
		cursor: pointer;
		transition: background-color 0.3s ease;
		color: black;
		width: 100rpx;
	}

	.cropper-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.7);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.cropper-container {
		position: relative;
		width: 80vw;
		height: 80vw;
		max-width: 400px;
		max-height: 400px;
		background: #000;
		border-radius: 10px;
		overflow: hidden;
		box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
	}

	.movable-area {
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;
		background: #000;
	}

	.movable-image {
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
	}

	.hidden-canvas {
		position: fixed;
		left: -9999px;
		width: 300px;
		height: 300px;
	}

	/* 
.cropper-controls {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.control-btn {
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    transition: 0.3s;
}

.zoom-btn {
    background: #f0f0f0;
    color: #333;
}

.cancel-btn {
    background: #ff4d4f;
    color: white;
}

.confirm-btn {
    background: #4caf50;
    color: white;
}

.control-btn:hover {
    opacity: 0.8;
}

.cropper-controls {
  display: flex;
  justify-content: space-around;
  padding: 12px;
  background: #f8f8f8;
  border-top: 1px solid #ddd;
 */

	.control-btn {
		flex: 1;
		margin: 0 8px;
		padding: 12px 0;
		font-size: 16px;
		font-weight: bold;
		border-radius: 8px;
		border: none;
		text-align: center;
		cursor: pointer;
	}

	.zoom-out,
	.zoom-in {
		background: #007aff;
		color: white;
	}

	.cancel {
		background: #ccc;
		color: black;
	}

	.confirm {
		background: #28a745;
		color: white;
	}

	.control-btn:active {
		opacity: 0.8;
	}

	.loading-container {
		margin-bottom: 20rpx;
	}

	.progress-container {
		width: 100%;
		margin-top: 10px;
		text-align: center;
	}

	.progress-bar {
		width: 90%;
		height: 40px;
		background: #e0e0e0;
		border-radius: 5px;
		overflow: hidden;
		margin: 0 auto;
	}

	.progress {
		height: 100%;
		background: #4caf50;
		/* 绿色进度条 */
		width: 0%;
		transition: width 0.3s ease-in-out;
	}

	.upload-status {
		display: block;
		margin-top: 5px;
		font-size: 14px;
		color: #666;
	}

	:root {
		--primary-color: #4361ee;
		--secondary-color: #3a0ca3;
		--accent-color: #f72585;
		--light-color: #f8f9fa;
		--dark-color: #212529;
		--success-color: #4cc9f0;
		--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.1);
		--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.15);
		--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.2);
		--transition: all 0.3s ease;
	}

	/* 页面容器 */
	.avatar-page {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(135deg, #a6caff 0%, #fff9fc 100%);
		overflow: hidden;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	/* 装饰圆圈 */
	.decor-circle {
		position: absolute;
		border-radius: 50%;
		background: rgba(67, 97, 238, 0.05);
		z-index: 0;
	}

	.circle-1 {
		width: 300rpx;
		height: 300rpx;
		top: -100rpx;
		left: -100rpx;
	}

	.circle-2 {
		width: 200rpx;
		height: 200rpx;
		bottom: 50rpx;
		right: -50rpx;
		background: rgba(244, 114, 182, 0.05);
	}

	.circle-3 {
		width: 150rpx;
		height: 150rpx;
		top: 30%;
		right: 20%;
		background: rgba(76, 201, 240, 0.05);
	}



	/* 内容包装 */
	.content-wrapper {
		position: relative;
		/* 添加相对定位作为loading的定位基准 */
		z-index: 1;
		width: 100%;
		max-width: 600rpx;
		background: white;
		border-radius: 24rpx;
		padding: 40rpx;
		box-shadow: var(--shadow-md);
		display: flex;
		flex-direction: column;
		align-items: center;
		overflow: hidden;
		/* 防止loading溢出圆角 */
	}

	/* 标题区 */
	.title-container {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: var(--dark-color);
		display: block;
		margin-bottom: 8rpx;
	}

	.subtitle {
		font-size: 24rpx;
		color: var(--dark-color);
		opacity: 0.7;
	}

	/* 头像展示区 */
	.avatar-display {
		position: relative;
		margin-bottom: 40rpx;
	}

	.avatar-frame {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		overflow: hidden;
		border: 4rpx solid white;
		box-shadow: var(--shadow-sm);
		position: relative;
		z-index: 2;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-shadow {
		position: absolute;
		width: 220rpx;
		height: 220rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
		opacity: 0.2;
		top: -10rpx;
		left: -10rpx;
		z-index: 1;
		filter: blur(10rpx);
	}

	/* 按钮区 */
	.action-buttons {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.upload-btn {
		height: 80rpx;
		border: none;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: var(--transition);
		box-shadow: var(--shadow-sm);
	}

	.select-btn {
		background: white;
		color: var(--primary-color);
		border: 1rpx solid var(--primary-color);
	}

	.select-btn:active {
		background: rgba(67, 97, 238, 0.1);
		transform: translateY(2rpx);
	}

	/* 	.confirm-btn {
		background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
		color: white;
	} */

	.confirm-btn:active:not(:disabled) {
		transform: translateY(2rpx);
		box-shadow: var(--shadow-sm);
	}

	.confirm-btn:disabled {
		opacity: 0.7;
	}

	.iconfont {
		margin-right: 10rpx;
		font-size: 32rpx;
	}

	/* 进度条 */
	.progress-container {
		width: 100%;
		margin-top: 20rpx;
	}

	.progress-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.progress-text {
		font-size: 24rpx;
		color: var(--dark-color);
		opacity: 0.7;
	}

	.progress-percent {
		font-size: 24rpx;
		font-weight: bold;
		color: var(--primary-color);
	}

	.progress-bar {
		width: 100%;
		height: 8rpx;
		background: #e9ecef;
		border-radius: 4rpx;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		border-radius: 4rpx;
		transition: width 0.3s ease;
		background: linear-gradient(to right, var(--primary-color), var(--accent-color));
	}

	/* 响应式调整 */
	@media (min-width: 768px) {
		.content-wrapper {
			padding: 60rpx;
		}

		.avatar-frame {
			width: 250rpx;
			height: 250rpx;
		}

		.avatar-shadow {
			width: 270rpx;
			height: 270rpx;
		}
	}
</style>